// ignore_for_file: avoid_print

import 'dart:io';

void main() async {
  Map pageData = await createPage('main', '主界面', '');
  await initMain(pageData);
  print('------main.dart初始化成功-----');
}

initMain(Map pageData) async {
  File mainFile = File('lib/main.dart');

  await mainFile.writeAsString(
      "import 'package:flutter_localizations/flutter_localizations.dart';\n"
      "import 'package:flutter/services.dart';\n"
      "import 'package:kmxy_base/base/base_package.dart';\n"
      "import 'package:${pageData['pageManagePackageFile'].path.replaceAll('lib', pageData['packageName'])}';\n"
      "void main() {\n"
      "WidgetsFlutterBinding.ensureInitialized();\n"
      "SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])\n"
      ".then((_) {\n"
      "runApp(const Main());\n"
      "});\n"
      "}\n"
      "\n"
      "class Main extends MainBase {\n"
      "const Main({Key? key}) : super(key: key);\n"
      "\n"
      "@override\n"
      "Iterable<LocalizationsDelegate> localizationsDelegates() {\n"
      "return [\n"
      "const CupertinoLocalizationsDelegate(),\n"
      "GlobalMaterialLocalizations.delegate,\n"
      "GlobalWidgetsLocalizations.delegate,\n"
      "];\n"
      "}\n"
      "\n"
      "@override\n"
      "initData() {}\n"
      "\n"
      "@override\n"
      "ScreenDefault setDefaultWH() {\n"
      "return ScreenDefault(375, 812);\n"
      "}\n"
      "\n"
      "@override\n"
      "Widget setStartPage(BuildContext context) {\n"
      "return MainPage();\n"
      "}\n"
      "\n"
      "@override\n"
      "String setTitle() {\n"
      "return '${pageData['packageName']}';\n"
      "}\n"
      "}");
}

Future<Map> createPage(
    String fileName, String titleName, String pagePath) async {
  // page_manage.dart
  File pageManageFile = File('lib/page/page_manage.dart');
  if (!await pageManageFile.exists()) {
    await pageManageFile.create(recursive: true);
    pageManageFile.writeAsString('part of page_manage_package;');
  }

  // page_manage_package.dart
  File pageManagePackageFile = File('lib/page/page_manage_package.dart');
  if (!await pageManagePackageFile.exists()) {
    await pageManagePackageFile.create(recursive: true);
    pageManagePackageFile.writeAsString('library page_manage_package;\n'
        "import 'package:kmxy_base/base/base_package.dart';\n"
        "part 'page_manage.dart';");
  }

  // xxx_page_state.dart
  File stateFile =
      File('lib/page/$pagePath/$fileName/${fileName}_page_state.dart');
  await stateFile.create(recursive: true);

  // xxx_page_view.dart
  File viewFile =
      File('lib/page/$pagePath/$fileName/${fileName}_page_view.dart');
  await viewFile.create(recursive: true);

  String className = "";

  for (int i = 0; i < fileName.length; i++) {
    if (i == 0) {
      className += fileName[i].toUpperCase();
    } else if (fileName[i] == "_") {
      className += fileName[i + 1].toUpperCase();
      i++;
    } else {
      className += fileName[i];
    }
  }

  String packageName = '';
  List<String> readAsLines = await File('pubspec.yaml').readAsLines();
  for (String line in readAsLines) {
    if (line.contains("name:")) {
      packageName = line.replaceAll('name:', '').trim();
      break;
    }
  }

  // page_manage.dart
  await pageManageFile.writeAsString(
      "\n"
      "\n"
      "/// $titleName界面\n"
      "// ignore: must_be_immutable\n"
      "class ${className}Page extends BasePage {\n"
      "${className}Page({Key? key, arguments}) : super(key: key, arguments: arguments);\n"
      "@override\n"
      "${className}PageView createState() => ${className}PageView();\n"
      "}",
      mode: FileMode.append);

  // page_manage_package.dart
  String readAsString = await pageManagePackageFile.readAsString();
  readAsString = readAsString
      .replaceAll(' ', '')
      .replaceAll("part'page_manage.dart';", '')
      .replaceAll(';', ';\n')
      .replaceAll('library', 'library ')
      .replaceAll('import', 'import ');

  await pageManagePackageFile.writeAsString("$readAsString"
      "import 'package:${viewFile.path.replaceAll('lib', packageName)}';\n"
      "part 'page_manage.dart';");

  // xxx_page_state.dart
  await stateFile.writeAsString(
      "import 'package:${pageManagePackageFile.path.replaceAll('lib', packageName)}';\n"
      "import 'package:kmxy_base/base/base_package.dart';\n"
      "abstract class ${className}PageState extends BasePageState<${className}Page> {\n"
      "\n"
      "@override\n"
      "initData() {}\n"
      "\n"
      "@override\n"
      "destroyData() {}\n"
      "\n"
      "\n"
      "}");

  // xxx_page_view.dart
  await viewFile.writeAsString("import '${fileName}_page_state.dart';\n"
      "import 'package:kmxy_base/base/base_package.dart';\n"
      "class ${className}PageView extends ${className}PageState {\n"
      "@override\n"
      "Widget setPageContent(BuildContext context) {\n"
      "return Scaffold(\n"
      "appBar: AppBar(\n"
      "centerTitle: true,\n"
      "title: Text(\n"
      "'$titleName',\n"
      "style: TextStyle(\n"
      "color: Colors.white,\n"
      "fontSize: 16.sp,\n"
      "fontWeight: FontWeight.w700,\n"
      "),\n"
      "),\n"
      "),\n"
      "body: SafeArea(\n"
      "child: Container(),\n"
      "),\n"
      ");\n"
      "}\n"
      "}");
  return {
    'pageManagePackageFile': pageManagePackageFile,
    'packageName': packageName,
  };
}
